<template>
    <div class="chart-container" v-show="isVisible">
      <div class="chart-wrapper">
        <div ref="mainChart" class="chart-item"></div>
      </div>
      <div class="chart-wrapper">
        <div ref="countChart" class="chart-item"></div>
      </div>
    </div>
  </template>
  
  <script setup>
  import * as echarts from 'echarts';
  import { onMounted, onUnmounted, nextTick, ref, watch } from 'vue';
  
  const props = defineProps({
    isVisible: {
      type: Boolean,
      default: true
    }
  });
  
  // DOM引用
  const mainChart = ref(null);
  const countChart = ref(null);
  
  // 图表实例
  let myChart = null;
  let countChartInstance = null;
  let timer = null;
  let resizeObserver = null;
  
  // 数据获取
  const fetchChartData = async () => {
    try {
      const res = await window.ipcRenderer.invoke('sendMain', JSON.stringify({ 
        type: 'getCountryCounts' 
      }));
      return res.map(item => ({
        name: item.country || '未查询国家',
        value: item.count,
      }));
    } catch (error) {
      console.error('获取国家数据失败:', error);
      return [];
    }
  };
  
  const fetchCountData = async () => {
    try {
      const res = await window.ipcRenderer.invoke('sendMain', JSON.stringify({ 
        type: 'getCount' 
      }));
      return res?.map(item => ({
        type: item.type === 1 ? '采集数量' : item.type === 2 ? '已查验数量' : '已上传数量',
        count: item.count
      })) || [];
    } catch (error) {
      console.error('获取计数数据失败:', error);
      return [];
    }
  };
  
  // 图表初始化
  const initCharts = async () => {
    await nextTick();
    
    if (!mainChart.value || !countChart.value) {
      console.warn('图表容器未找到，延迟初始化');
      setTimeout(initCharts, 100);
      return;
    }
  
    if (!myChart) {
      myChart = echarts.init(mainChart.value);
      myChart.showLoading();
    }
    if (!countChartInstance) {
      countChartInstance = echarts.init(countChart.value);
      countChartInstance.showLoading();
    }
  
    updateCharts();
  };
  
  // 图表更新
  const updateCharts = async () => {
    try {
      // 更新国家分布图
      const countryData = await fetchChartData();
      myChart?.setOption({
        tooltip: { trigger: 'item' },
        legend: {
          top: '5%',
          left: 'center',
          formatter: name => {
            const item = countryData.find(d => d.name === name);
            return `${name}(${item?.value ?? 0})`;
          },
          textStyle: { fontSize: 14, color: '#333' }
        },
        series: [{
          name: '国家分布',
          type: 'pie',
          radius: ['40%', '70%'],
          minAngle: 3,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
          },
          label: { show: false },
          emphasis: { label: { show: true, fontSize: 16 } },
          data: countryData
        }]
      });
      myChart?.hideLoading();
  
      // 更新数量统计图
      const countData = await fetchCountData();
      countChartInstance?.setOption({
        tooltip: { trigger: 'axis' },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: countData.map(d => d.type),
          axisLabel: { 
            rotate: 45,
            interval: 0,
            formatter: (value) => value.split('').join('\n') // 垂直文字
          }
        },
        yAxis: { type: 'value' },
        series: [{
          type: 'bar',
          data: countData.map(d => d.count),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#36D1DC' },
              { offset: 1, color: '#5B86E5' }
            ])
          }
        }]
      });
      countChartInstance?.hideLoading();
    } catch (error) {
      console.error('图表更新失败:', error);
    }
  };
  
  // 自适应处理
  const setupResizeHandler = () => {
    resizeObserver = new ResizeObserver(() => {
      myChart?.resize();
      countChartInstance?.resize();
    });
  
    if (mainChart.value) resizeObserver.observe(mainChart.value);
    if (countChart.value) resizeObserver.observe(countChart.value);
  };
  
  // 显示状态监听
  watch(() => props.isVisible, (visible) => {
    if (visible) {
      nextTick(() => {
        myChart?.resize();
        countChartInstance?.resize();
      });
    }
  });
  
  // 生命周期
  onMounted(async () => {
    if (props.isVisible) {
      await initCharts();
      setupResizeHandler();
    }
    timer = setInterval(updateCharts, 5000);
  });
  
  onUnmounted(() => {
    myChart?.dispose();
    countChartInstance?.dispose();
    clearInterval(timer);
    resizeObserver?.disconnect();
  });
  </script>
  
  <style scoped>
  .chart-container {
    display: flex;
    height: 100%;
    width: 100%;
    gap: 16px;
    padding: 16px;
    box-sizing: border-box;
  }
  
  .chart-wrapper {
    flex: 1;
    min-width: 0; /* 重要：防止内容溢出 */
    height: 100%;
    position: relative;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  }
  
  .chart-item {
    width: 100%;
    height: 100%;
    min-height: 300px;
  }
  </style>